﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using BGSpaceShooterServer;
using Microsoft.Xna.Framework.Input;

namespace BGSpaceShooter
{
    public class NetworkController
    {

        public NetworkController(string ipAddress, int port)
        {
            Server = new Server(port, IPAddress.Parse(ipAddress));
            ObserverManager = new ObserverManager();
        }

        public Server Server { get; set; }


        protected ObserverManager ObserverManager { get; set; }

        public void RegisterStatusObservers(IEnumerable<IStatusObserver> list)
        {
            foreach (IStatusObserver statusObserver in list)
            {
                ObserverManager.Register(statusObserver);
            }
        }

        public void RegisterStateObservers(IEnumerable<IStateObserver> list)
        {
            foreach (IStateObserver stateObserver in list)
            {
                ObserverManager.Register(stateObserver);
            }
        }

        public void Update(ushort playerId, List<Keys> userInput)
        {
            IEnumerable<ServerToClientPacket> response = Server.Read();

            ObserverManager.Notify(Server.GetServerStatusResponses(response));
            ObserverManager.Notify(Server.GetServerStateResponses(response));

            SendUserInputToServer(playerId, userInput);
        }

        public void SendUserInputToServer(ushort playerId, List<Keys> userInput)
        {
            Server.SendUpdateRequest(playerId, userInput);
        }

        public void SendChatToServer(ushort playerId, IEnumerable<string> messages)
        {
            foreach (string message in messages)
            {
                Server.SendChatMessage(playerId, playerId + "> " + message);
            }
        }

        /// <summary>
        /// Wysyła żądanie przyłączenia nowego gracza.
        /// </summary>
        /// <param name="responses">Lista obiektów do utworzenia</param>
        /// <returns>ID gracza</returns>
        public int RegisterNewPlayer(out List<ServerStatusResponse> responses)
        {
            responses = new List<ServerStatusResponse>();
            int id = Server.RequestJoin();
            if (id >= 0)
            {
                responses = Server.StartGame();
            }
            return id;
        }
    }
}
